package com.app.teaware.ware;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.app.teaware.R;
import com.app.teaware.basis.BasisActivity;
import com.app.teaware.basis.Constants;
import com.app.teaware.bean.BasisBean;
import com.app.teaware.bean.GoodsListData;
import com.app.teaware.bean.GoodsWorks;
import com.app.teaware.bean.KWListBean;
import com.app.teaware.bean.LoginBean;
import com.app.teaware.bean.UnitListBean;
import com.app.teaware.bean.WareListData;
import com.app.teaware.goods.GoodsDataActivity;
import com.app.teaware.goods.GoodsListActivity;
import com.app.teaware.greendao.GreenDaoUtils;
import com.app.teaware.util.ReceiverUtils;
import com.app.teaware.util.UHFUtil;
import com.google.gson.Gson;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;

import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import my.ActivityTool;
import my.DialogUtils;
import my.MathUtils;
import my.TimeUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/***
 * 添加入库资料
 * **/
public class EditWareInfoActivity extends BasisActivity {

    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    @BindView(R.id.edit_code)
    EditText edit_code;
    @BindView(R.id.edit_name)
    EditText edit_name;
    @BindView(R.id.edit_specs)
    EditText edit_specs;

    @BindView(R.id.text_unit)
    TextView text_unit;     //旧：edit_price

    @BindView(R.id.edit_num)
    EditText edit_num;
    @BindView(R.id.text_weight)
    TextView text_weight;
    @BindView(R.id.edit_qrcode)
    EditText edit_qrcode;
    @BindView(R.id.edit_kw)
    EditText edit_kw;

    String gid;
    String cid;
    String gunp;

    KWListBean kwListBean;

    WareListData works;
    String fTotalWeight = "0";    //整箱货品的重量，单位：kg

    UnitListBean unitListBean = null;   //所有货品单位


    public  static void toEdit(Activity context,String cid, WareListData works, int requst){
        Bundle extras = new Bundle();
        extras.putString("cid",cid);
        extras.putSerializable("works", works);
        ActivityTool.skipActivityForResult(context, EditWareInfoActivity.class,extras,requst);
    }


    @Override
    public void initViews() {
        // TODO Auto-generated method stub
        super.initViews();
        setContentView(R.layout.edit_ware_activity);
        setTitle("编辑");
        setTitleLeftButton(null);

        //监测数量变化事件
        edit_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable edit) {
                //edit  输入结束呈现在输入框中的信息
                if(resultGoodsData != null && !edit_num.getText().toString().isEmpty() && !text_unit.getText().toString().isEmpty()) {
                    //规格字符串拼接
                    edit_specs.setText(edit_num.getText().toString() + resultGoodsData.getGun() + "/" + text_unit.getText().toString());
                    //重量自动计算
                    fTotalWeight =  MathUtils.div(MathUtils.multiply(resultGoodsData.getGwt(),edit_num.getText().toString()),"1000");
                    text_weight.setText(fTotalWeight);
                }
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.initData(savedInstanceState);
        works = (WareListData) getIntent().getSerializableExtra("works");
        cid= getIntent().getStringExtra("cid");
//        UHFUtil.allTriggerModeOpen();
        //ice 库位改为扫描或手工输入，不是原来列表中选择，所以无需获取库位信息了
        //intSpinner();

        if(works == null){
            works = new WareListData();
        }else {
            initWorks();
        }
        //ice 3 获取所有单位
        unitListBean = GreenDaoUtils.getUnitListBean();
    }


    @OnClick(R.id.view_price)
    void UnitBtn() {
        if(unitListBean == null) return;
        new QMUIDialog.MenuDialogBuilder(mContext)
                .setSkinManager(QMUISkinManager.defaultInstance(mContext))
                .addItems(unitListBean.getAllUnits(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        text_unit.setText(unitListBean.getAllUnits()[which]);
                        if(resultGoodsData != null && !edit_num.getText().toString().isEmpty() && !text_unit.getText().toString().isEmpty()) {
                            //规格字符串拼接
                            edit_specs.setText(edit_num.getText().toString() + resultGoodsData.getGun() + "/" + text_unit.getText().toString());
                            //重量自动计算
                            fTotalWeight =  MathUtils.div(MathUtils.multiply(resultGoodsData.getGwt(),edit_num.getText().toString()),"1000");
                            text_weight.setText(fTotalWeight);
                        }
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }


    void initWorks(){
        edit_code.setText(works.getGno());
        edit_name.setText(works.getGna());
        edit_specs.setText(works.getGsp());
        text_unit.setText(works.getGun());
        edit_num.setText(""+works.getGnu1());
        text_weight.setText(""+works.getGwt1());
        gid = works.getGid();
        edit_qrcode.setText(works.getRfid());
        edit_kw.setText(works.getWms2());
    }



    @OnClick({R.id.btn_code,R.id.btn_scan,R.id.btn_specs})
    void btnOnclick(){
        ActivityTool.skipActivityForResult(mContext, GoodsDataActivity.class,Constants.GOODSDATARESULT);
    }



    GoodsListData resultGoodsData = null;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Constants.GOODSDATARESULT){
            resultGoodsData = (GoodsListData) data.getSerializableExtra("data");
            if(resultGoodsData != null){
                edit_code.setText(resultGoodsData.getGno());
                edit_name.setText(resultGoodsData.getGna());
                //edit_specs.setText(resultGoodsData.getGsp());
                //edit_price.setText(resultGoodsData.getGun());
                gid = resultGoodsData.getGid();
                gunp = resultGoodsData.getGun();


                if(resultGoodsData != null && !edit_num.getText().toString().isEmpty() && !text_unit.getText().toString().isEmpty()) {
                    //规格字符串拼接
                    edit_specs.setText(edit_num.getText().toString() + resultGoodsData.getGun() + "/" + text_unit.getText().toString());
                    //重量自动计算
                    fTotalWeight =  MathUtils.div(MathUtils.multiply(resultGoodsData.getGwt(),edit_num.getText().toString()),"1000");
                    text_weight.setText(fTotalWeight);
                }
            }
        }
    }

    //ice 硬件相关，rfid读卡成功通知
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();

            switch (action){
                case Constants.ACTION_UHF_RESULT_SEND:
                    Parcelable[] tagInfos = intent.getParcelableArrayExtra(Constants.EXTRA_TAG_INFO);
                    String qrcode = UHFUtil.getEPCId(tagInfos).trim().toUpperCase(Locale.ROOT);

                    if(!TextUtils.isEmpty(qrcode)) {
//                        edit_qrcode.setText(qrcode);
                    }
                    break;

                case Constants.ACTION_SCANNER_RESULT_SEND:
                    final  String scanResult_1 = intent.getStringExtra("SCAN_BARCODE1");
                    final  String scanResult_2 = intent.getStringExtra("SCAN_BARCODE2");
                    final  int barcodeType = intent.getIntExtra("SCAN_BARCODE_TYPE",-1);
                    final String scanStatus = intent.getStringExtra("SCAN_STATE");
                    if("ok".equals(scanStatus)) {
                        System.out.println("ice 硬件扫码结果：" + scanResult_1.trim());
                        edit_kw.setText(scanResult_1.trim());
                    }
                    break;
            }


        }//end onReceiver
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ReceiverUtils.unRegisterReceiver(mContext,mResultReceiver);
    }


    @Override
    protected void onResume() {
        super.onResume();
        ReceiverUtils.registerUHFAndScannerReceiver(mContext,mResultReceiver);
    }

    GoodsWorks submit;
    boolean idOk;
    @OnClick(R.id.btn_add)
    void btnAdd(){
        try {
            if (TextUtils.isEmpty(edit_code.getText().toString())) {
                showToast("单号不能为空");
                return;
            }
            if (TextUtils.isEmpty(edit_num.getText().toString())) {
                showToast("数量不能为空");
                return;
            }
            if (Double.valueOf(edit_num.getText().toString()) == 0) {
                showToast("数量不为0");
                return;
            }
            if (TextUtils.isEmpty(text_weight.getText().toString())) {
                showToast("重量不能为空");
                return;
            }

            if (Double.valueOf(text_weight.getText().toString()) == 0) {
                showToast("重量不为0");
                return;
            }
            if (TextUtils.isEmpty(edit_qrcode.getText().toString())) {
                showToast("箱码不能为空");
                return;
            }
            if (TextUtils.isEmpty(edit_kw.getText().toString())) {
                showToast("库位不能为空");
                return;
            }
            submit = new GoodsWorks();
            submit.setAid(LoginBean.getInstance().getAcode());
            submit.setBfs("4");            //1工单/2领料/3退料/4入库
            submit.setCid(cid);
            submit.setGid(gid);              //货品id
            submit.setGna(edit_name.getText().toString());       //货品名称
            submit.setGno(edit_code.getText().toString());       //货品编码
            submit.setGun(text_unit.getText().toString());       //整件单位
            submit.setGnu(edit_num.getText().toString());        //包装数量
            submit.setGsp(edit_specs.getText().toString());      //货品规格
            submit.setGunp(gunp);
            submit.setGwt(text_weight.getText().toString());     //整件重量
            if(resultGoodsData != null) {
                submit.setGwtp(resultGoodsData.getGwt().substring(0,resultGoodsData.getGwt().length()-1));
            }

            submit.setMdt(TimeUtils.getCurrentTimeByFormat("yyyy-MM-dd"));
            submit.setRfid(edit_qrcode.getText().toString().trim()); //箱码
            submit.setSid(works.getSid());
            submit.setWms(edit_kw.getText().toString().trim()); //库位
            idOk = true;
        }
        catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "保存失败！", Toast.LENGTH_SHORT).show();
        }
    }


    @OnClick(R.id.btn_submit)
    void btnSubmit(){
        btnAdd();
        if(!idOk){
            return;
        }
        MyParams params = new MyParams();
        showProgress();
        Gson gson = new Gson();
        String a = gson.toJson(submit);
        params.putJson(a);

        MyHttpUtils.postJson(Constants.URL_EXCEL_UPDATE, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if (isFinishing()) return;
                        BasisBean basisBean = (BasisBean) result;
                        showToast(((BasisBean) result).getStatusInfo());
                        setResult(GoodsListActivity.WARNLISTRESULT);
                        finish();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        if (isFinishing()) return;
                        dismissProgress();
//                            super.onFailure(httpWhat, result);
                        if(result != null){
                            DialogUtils.showErrorDialog(mContext,((BasisBean) result).getStatusInfo());
                        }

                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, BasisBean.class);
    }

}
